/*
 * PisoMundo.cpp
 *
 *  Created on: 08/05/2013
 *      Author: gonzalo
 */

#include "PisoMundo.h"

PisoMundo::PisoMundo(GLuint  program, GLfloat range) :
		Figure(program) {

	this->vertex_buffer_size = 4;
	this->normal_buffer_size = 4;
	this->index_buffer_size = 4;
	this->vertex_buffer = new GLfloat[this->vertex_buffer_size * 3];
	this->normal_buffer = new GLfloat[this->vertex_buffer_size * 3];
	this->index_buffer = new GLuint[4];

	set_coords3(vertex_buffer, 0, range, range, 0.0);
	set_coords3(vertex_buffer, 1, -range, range, 0.0);
	set_coords3(vertex_buffer, 2, -range, -range, 0.0);
	set_coords3(vertex_buffer, 3, range, -range, 0.0);

	set_coords3(normal_buffer, 0, 0.0, 0.0, 1.0);
	set_coords3(normal_buffer, 1, 0.0, 0.0, 1.0);
	set_coords3(normal_buffer, 2, 0.0, 0.0, 1.0);
	set_coords3(normal_buffer, 3, 0.0, 0.0, 1.0);

	for(uint i = 0; i < 4; i++){
		this->index_buffer[i] = i;
	}

}

PisoMundo::~PisoMundo() {

	delete [] this->vertex_buffer;
	delete [] this->normal_buffer;
}

void PisoMundo::draw(GLuint program, glm::mat4 & world_matrix) {
	glm::mat4 matriz = world_matrix * this->model_matrix;

	// Normal Matrix
	glm::mat3 normal_matrix = glm::mat3(1.0f);
	if (this->view_matrix != NULL) {
		glm::mat4 aux = (*this->view_matrix) * world_matrix;
		for (int i = 0; i < 3; i++)
			for (int j = 0; j < 3; j++)
				normal_matrix[i][j] = aux[i][j];
	}

	// Bind Normal Matrix
	GLuint location_normal_matrix = glGetUniformLocation(program, "NormalMatrix");
	if (location_normal_matrix >= 0) {
		glUniformMatrix3fv(location_normal_matrix, 1, GL_FALSE, &normal_matrix[0][0]);
	}

	// Bind Model Matrix
	GLuint location_model_matrix = glGetUniformLocation(program, "ModelMatrix");
	if (location_model_matrix >= 0) {
		glUniformMatrix4fv(location_model_matrix, 1, GL_FALSE, &matriz[0][0]);
	}

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_NORMAL_ARRAY);

	glVertexPointer(3, GL_FLOAT, 0, vertex_buffer);
	glNormalPointer(GL_FLOAT, 0, vertex_buffer);

	glDrawElements(GL_QUADS, index_buffer_size, GL_UNSIGNED_INT, index_buffer);

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
}
